import { _decorator, Component, Node, Button, Label, Slider } from 'cc';
import { MapRenderer } from './render/MapRenderer';
import { ResourceLoadManager } from './render/ResourceLoadManager';
import { UIManager } from './ui/UIManager';
import { ProgressController } from './ui/ProgressController';
import { BuildingType, CommandType, EntityType, PlayerType, UnitType } from '../../battle/Enums';
import { getBuildingConfig, getUnitConfig, ResourceConfig, MapSettings, BasePositionConfigs } from '../../battle/Const';
import { BattleResultData, BuildCommandParam, CommandParam, CommandParamMap } from '../../battle/Model';
import { CommandManager } from './CommandManager';
import { PlayerStatsManager } from './stats/PlayerStatsManager';
import { LOG } from '../../ConsoleLogCtrl';

const { ccclass, property } = _decorator;

/**
 * 战斗场景
 * 作为战斗客户端场景的控制器，负责处理战斗命令并调用相应的渲染组件
 */
@ccclass('BattleScene')
export class BattleScene extends Component {
    @property(MapRenderer)
    public mapRenderer: MapRenderer = null;

    @property(UIManager)
    public uiManager: UIManager = null;

    @property(ProgressController)
    public progressController: ProgressController = null;

    /** 命令管理器实例 */
    private _commandManager: CommandManager = null;

    /**
     * 组件加载时初始化渲染组件
     */
    onLoad() {
        LOG.log('BattleScene onLoad: 初始化渲染组件');
        this.initRenderComponents();
        this.initCommandManager();
        ResourceLoadManager.preloadAllAtlases((err, results) => {
            if (err) {
                LOG.error('BattleScene: 预加载所有图集失败', err);
                return;
            }
            LOG.log('BattleScene: 预加载所有图集成功');
        });
    }

    /**
     * 组件销毁时清理资源
     */
    onDestroy() {
        if (this._commandManager) {
            // 移除回调注册
            this._commandManager.unregisterDispatchCallback((cmd: CommandType, data?: CommandParam<keyof CommandParamMap>) => {
                this.handleBattleCommandInternal(cmd, data);
            });
        }
        LOG.log('BattleScene: 组件已销毁');
    }

    /**
     * 初始化命令管理器
     */
    private initCommandManager() {
        // 获取命令管理器单例
        this._commandManager = CommandManager.getInstance();

        // 注册命令分发回调
        this._commandManager.registerDispatchCallback((cmd: CommandType, data?: CommandParam<keyof CommandParamMap>) => {
            this.handleBattleCommandInternal(cmd, data);
        });

        LOG.log('BattleScene: CommandManager 初始化完成');
    }

    /**
     * 初始化渲染组件
     */
    private initRenderComponents() {
        // 初始化UIManager
        if (!this.uiManager) {
            LOG.log('创建UIManager组件');
            const uiNode = new Node('UIManager');
            uiNode.parent = this.node;
            this.uiManager = uiNode.addComponent(UIManager);
        }

        // 初始化MapRenderer
        if (!this.mapRenderer) {
            LOG.log('创建MapRenderer组件');
            const mapNode = new Node('MapRenderer');
            mapNode.parent = this.node;
            this.mapRenderer = mapNode.addComponent(MapRenderer);
        }
        this.mapRenderer.uiManager = this.uiManager;

        // 设置进度控制器的回调
        if (this.progressController) {
            this.progressController.setResetCallback(() => {
                this.reset();
            });
            this.progressController.setRenderCallback(() => {
                this.mapRenderer.renderAllNodes();
            });
        }
    }

    /**
     * 处理战斗命令的接口方法
     */
    public handleBattleCommand(cmd: CommandType, data?: CommandParam<keyof CommandParamMap>, checkResult?: { valid: boolean; error?: string }) {
        if (this._commandManager) {
            // 将命令发送给命令管理器
            this._commandManager.receiveCommand(cmd, data);
        } else {
            LOG.error('CommandManager 未初始化，无法处理命令');
            // 降级处理：直接执行命令
            this.handleBattleCommandInternal(cmd, data);
        }
    }

    /**
     * 批量处理战斗命令的接口方法（用于战报回放）
     * @param commands 命令数组
     */
    public handleBattleCommandBatch(commands: CommandParam<keyof CommandParamMap>[]) {
        if (this._commandManager) {
            LOG.log(`BattleScene: 开始批量处理 ${commands.length} 个战斗命令`);
            this._commandManager.clearAllCommands();
            // 将命令数组发送给命令管理器
            this._commandManager.receiveCommandBatch(commands);
            // 接收完毕后立即开始分发命令
            this._commandManager.play();
            // 启动进度条更新
            if (this.progressController) {
                this.progressController.startProgressUpdate();
                this.progressController.updateControlsVisibility();
            }
            LOG.log(`BattleScene: 批量命令处理完成，开始分发`);
        } else {
            LOG.error('CommandManager 未初始化，无法批量处理命令');
            // 降级处理：逐个直接执行命令
            LOG.log('BattleScene: 使用降级模式逐个处理命令');
            for (const command of commands) {
                this.handleBattleCommandInternal(command.type, command);
            }
        }
    }

    /**
     * 内部命令处理方法
     */
    private handleBattleCommandInternal(cmd: CommandType, data: CommandParam<keyof CommandParamMap>) {

        let buildBaseCommands = []

        // 根据命令类型分发到不同的处理函数
        switch (cmd) {
            case CommandType.init:
                buildBaseCommands = this.handleInitCommand(data as CommandParam<CommandType.init>);
                break;
            case CommandType.move:
                this.handleMoveCommand(data as CommandParam<CommandType.move>);
                break;
            case CommandType.attack:
                this.handleAttackCommand(data as CommandParam<CommandType.attack>);
                break;
            case CommandType.build:
                this.handleBuildCommand(data as CommandParam<CommandType.build>);
                break;
            case CommandType.swap:
                this.handleSwapCommand(data as CommandParam<CommandType.swap>);
                break;
            case CommandType.heal:
                this.handleHealCommand(data as CommandParam<CommandType.heal>);
                break;
            case CommandType.collect:
                this.handleCollectCommand(data as CommandParam<CommandType.collect>);
                break;
            case CommandType.end:
                this.handleEndCommand(data as CommandParam<CommandType.end>);
                break;
            default:
                LOG.warn(`未处理的命令类型: ${cmd}`);
                break;
        }
        // 调用玩家统计信息
        const statsManager = PlayerStatsManager.getInstance();
        statsManager.handleCommandStats(data);

        // init命令时构建基地的统计
        if (buildBaseCommands.length > 0) {
            for (let data of buildBaseCommands) {
                this.handleBuildCommand(data);
                statsManager.handleCommandStats(data);
            }
        }
    }

    private handleInitCommand(data: CommandParam<CommandType.init>): CommandParam<CommandType.build>[] {
        LOG.log('初始化战场:', data);
        // 初始化地图渲染
        if (this.mapRenderer) {
            this.mapRenderer.renderMap(data);
        } else {
            LOG.error('mapRenderer为null，无法渲染地图');
        }

        // 创建两个基地命令
        const buildBaseCommands = this.createPlayerBaseCommands(data);

        // 显示初始化消息
        if (this.uiManager) {
            this.uiManager.showMessage('战场初始化完成', 'info');
        } else {
            LOG.error('uiManager为null，无法显示消息');
        }

        return buildBaseCommands;
    }

    private handleMoveCommand(data: CommandParam<CommandType.move>) {
        LOG.log('单位移动:', data);

        if (data?.param) {
            let finalPosition = this.mapRenderer.updateUnitPosition(data, !this._commandManager.isFastForwarding());

            // 显示移动消息，传递最终位置信息
            // this.showCommandLog(data, finalPosition);
        }
    }

    private handleAttackCommand(data: CommandParam<CommandType.attack>) {
        LOG.log('单位攻击:', data);

        if (data?.param) {
            let attackParam = data.param;
            let attackResult: any = null;

            if (attackParam.target && attackParam.target.type === EntityType.unit) {
                attackResult = this.mapRenderer.attackUnit(data);
            } else {
                attackResult = this.mapRenderer.attackBuilding(data);
            }

            // 显示攻击消息，如果是击杀则显示特殊消息
            this.showCommandLog(data, attackResult);
        }
    }

    private handleBuildCommand(data: CommandParam<CommandType.build>) {
        LOG.log('建造建筑:', data);

        // 处理建造逻辑
        if (data?.param) {
            let playerInfo = this.getPlayerInfo(data.player);
            let playerType = playerInfo.playerType;
            let position = this.mapRenderer.createBuilding(data, playerType, !this._commandManager.isFastForwarding());
            if (!position) {
                return;
            }
            // 显示建造消息
            this.showCommandLog(data, position);
        }
    }

    private handleSwapCommand(data: CommandParam<CommandType.swap>) {
        LOG.log('生产单位:', data);

        // 处理生产逻辑
        if (data?.param) {
            let playerInfo = this.getPlayerInfo(data.player);
            let playerType = playerInfo.playerType;
            let position = this.mapRenderer.createUnit(data, playerType, !this._commandManager.isFastForwarding());
            if (!position) {
                return;
            }

            // 显示生产消息
            this.showCommandLog(data, position);
        }
    }

    private handleHealCommand(data: CommandParam<CommandType.heal>) {

        LOG.log('单位治疗:', data);

        if (data?.param) {
            this.mapRenderer.healUnit(data, !this._commandManager.isFastForwarding());

            // 显示治疗消息
            this.showCommandLog(data);
        }
    }

    private handleCollectCommand(data: CommandParam<CommandType.collect>) {
        LOG.log('资源采集:', data);

        if (data?.param) {
            // 显示采集效果（可以添加粒子效果或动画）
            this.mapRenderer.collectResource(data, !this._commandManager.isFastForwarding());

            // 显示采集消息
            this.showCommandLog(data);
        }
    }

    private handleEndCommand(data: CommandParam<CommandType.end>) {
        LOG.log('游戏结束:', data);

        // 获取战斗结果数据
        if (data?.param) {
            const battleResult: BattleResultData = (data.param as { result: BattleResultData }).result;

            // 通过UIManager设置战斗结果到玩家统计面板
            if (this.uiManager) {
                this.uiManager.setBattleResult(battleResult);
            }
            this.progressController.updateControlsVisibility();
        }
    }

    /**
     * 获取玩家信息
     */
    public getPlayerInfo(playerId: string) {
        const statsManager = PlayerStatsManager.getInstance();
        const playerStats = statsManager.getPlayerStats(playerId);
        if (playerStats) {
            return {
                id: playerStats.getId(),
                playerType: playerStats.getPlayerType(),
                color: playerStats.getColor(),
                startPosition: playerStats.getStartPosition()
            };
        }
        return null;
    }

    /**
     * 创建玩家基地命令
     * @param data 初始化命令数据
     */
    private createPlayerBaseCommands(data: CommandParam<CommandType.init>): CommandParam<CommandType.build>[] {
        const initParam = data.param;
        const players = initParam.players;
        const buildBaseCommands: CommandParam<CommandType.build>[] = [];

        // 为每个玩家创建基地
        for (let i = 0; i < Math.min(players.length, 2); i++) {
            const playerId = players[i];
            const basePosition = BasePositionConfigs[initParam.map][i];

            // 构造基地建造命令数据
            const baseBuildData: CommandParam<CommandType.build> = {
                type: CommandType.build,
                player: playerId,
                round: data.round,
                param: {
                    self: {
                        type: EntityType.unit,
                        utype: UnitType.worker, // 使用建造兵类型作为占位符
                        id: -1 // 使用-1作为系统
                    },
                    target: {
                        type: EntityType.building,
                        utype: BuildingType.base,
                        id: 1 + i // 基地ID：1, 2
                    },
                    offsetPosition: basePosition // 直接使用基地位置
                }
            };

            // 添加到命令列表
            buildBaseCommands.push(baseBuildData);
        }

        return buildBaseCommands;
    }

    /**
     * 根据命令类型统一显示日志消息
     */
    public showCommandLog(data: CommandParam<keyof CommandParamMap>, extData?: any) {
        if (!this.uiManager || !data?.param) {
            return;
        }

        const playerInfo = this.getPlayerInfo(data.player);
        if (!playerInfo) {
            return;
        }
        const playerType = playerInfo.playerType;
        let message = '';

        switch (data.type) {
            case CommandType.attack:
                const attackParam = data.param as CommandParamMap[CommandType.attack];
                if (attackParam.self && attackParam.target) {
                    const selfConfig = this.getEntityConfig(attackParam.self);
                    const targetConfig = this.getEntityConfig(attackParam.target);

                    // 处理新的攻击结果格式
                    let isKilled = extData.isKilled;
                    let splashInfo = extData.splashInfo;
                    if (isKilled) {
                        // 击杀消息
                        message = ` <${data.player}> 的${selfConfig.name}${selfConfig.id}🔪击杀敌方${targetConfig.name}${targetConfig.id},获${targetConfig.killedAward}💎`;

                        // 添加溅射伤害信息
                        if (splashInfo && (splashInfo.killedCount > 0 || splashInfo.damagedCount > 0)) {
                            message += `💥溅射:`;
                            if (splashInfo.killedCount > 0) {
                                message += `击杀${splashInfo.killedCount}`;
                            }
                            if (splashInfo.damagedCount > 0) {
                                if (splashInfo.killedCount > 0) message += ',';
                                message += `伤害${splashInfo.damagedCount}`;
                            }
                        }
                    } else {
                        // 普通攻击消息
                        message = ` <${data.player}> 的${selfConfig.name}${selfConfig.id}⚔️攻击敌方${targetConfig.name}${targetConfig.id},伤${selfConfig.attack}🩸`;

                        // 添加溅射伤害信息
                        if (splashInfo && (splashInfo.killedCount > 0 || splashInfo.damagedCount > 0)) {
                            message += `💥溅射:`;
                            if (splashInfo.killedCount > 0) {
                                message += `击杀${splashInfo.killedCount}`;
                            }
                            if (splashInfo.damagedCount > 0) {
                                if (splashInfo.killedCount > 0) message += ',';
                                message += `伤害${splashInfo.damagedCount}`;
                            }
                        }
                    }
                }
                break;

            case CommandType.build:
                const buildParam = data.param as CommandParamMap[CommandType.build];
                if (buildParam.self && buildParam.target) {
                    const builderTargetConfig = this.getEntityConfig(buildParam.target);
                    const builderConfig = this.getEntityConfig(buildParam.self);
                    let position = extData as { x: number; y: number };
                    if (position) {
                        const buildPosition = position;
                        message = ` <${data.player}> 的${builderConfig.name}${builderConfig.id}🪓建造了${builderTargetConfig.name}${builderTargetConfig.id}在(${buildPosition.x}, ${buildPosition.y})`;
                    } else {
                        message = ` <${data.player}> 的${builderConfig.name}${builderConfig.id}🪓建造了${builderTargetConfig.name}${builderTargetConfig.id}`;
                    }
                }
                break;

            case CommandType.swap:
                const swapParam = data.param as CommandParamMap[CommandType.swap];
                if (swapParam.self && swapParam.target) {
                    const unitConfig = this.getEntityConfig(swapParam.target);
                    let position = extData as { x: number; y: number };
                    if (position) {
                        const swapPosition = position;
                        message = ` <${data.player}> 的基地💑生产了${unitConfig.name}${unitConfig.id}在(${swapPosition.x}, ${swapPosition.y})`;
                    } else {
                        message = ` <${data.player}> 的基地💑生产了${unitConfig.name}${unitConfig.id}`;
                    }
                }
                break;

            case CommandType.move:
                const moveParam = data.param as CommandParamMap[CommandType.move];
                if (moveParam.self) {
                    const unitConfig = this.getEntityConfig(moveParam.self);
                    let position = extData as { x: number; y: number };
                    if (position) {
                        const movePosition = position;
                        message = ` <${data.player}> 的${unitConfig.name}${unitConfig.id}🚶移动到(${movePosition.x}, ${movePosition.y})`;
                    } else {
                        message = ` <${data.player}> 的${unitConfig.name}${unitConfig.id}🚶移动`;
                    }
                }
                break;

            case CommandType.heal:
                const healParam = data.param as CommandParamMap[CommandType.heal];
                if (healParam.self && healParam.target) {
                    const healerConfig = this.getEntityConfig(healParam.self);
                    const healTargetConfig = this.getEntityConfig(healParam.target);
                    message = ` <${data.player}> 的${healerConfig.name}${healerConfig.id}💊治疗了${healTargetConfig.name}${healTargetConfig.id}, 补${healerConfig.attack}💖`;
                }
                break;

            case CommandType.collect:
                 const collectParam = data.param as CommandParamMap[CommandType.collect];
                 if (collectParam.self) {
                     const collectorConfig = this.getEntityConfig(collectParam.self);
                     const resourceType = collectParam.target.utype;
                     const resourceName = ResourceConfig[resourceType].name;
                     const resourceValue = ResourceConfig[resourceType].value;
                     const resourceIcon = ResourceConfig[resourceType].icon;
                     message = ` <${data.player}> 的${collectorConfig.name}${collectorConfig.id}⛏️采集了${resourceIcon}${resourceName}, 获${resourceValue}💎`;
                 }
                 break;

             case CommandType.end:
                 const endParam = data.param as CommandParamMap[CommandType.end];
                 if (endParam?.result) {
                     const battleResult = endParam.result;
                     const winner = battleResult.winner;
                     message = ` 🏆 游戏结束！获胜者: <${winner}>`;
                 }
                 break;

             default:
                 return;
        }

        if (message) {
            this.uiManager.showMessage(message, playerType);
        }
    }

    /**
     * 获取实体配置信息（单位或建筑）
     */
    private getEntityConfig(entity: { type: EntityType; utype: any; id: number }) {
        if (entity.type === EntityType.unit) {
            const unitConfig = getUnitConfig(entity.utype as UnitType);
            return {
                name: unitConfig.name,
                icon: unitConfig.icon,
                attack: unitConfig.attack,
                killedAward: unitConfig.killedAward,
                id: entity.id
            };
        } else {
            const buildingConfig = getBuildingConfig(entity.utype as BuildingType);
            return {
                name: buildingConfig.name,
                icon: buildingConfig.icon,
                attack: buildingConfig.attack,
                killedAward: buildingConfig.killedAward,
                id: entity.id
            };
        }
    }

    /**
     * 重置战斗场景
     */
    public reset() {
        LOG.log('BattleScene: 开始重置战斗场景');

        // 清空所有渲染对象（单位和建筑）
        if (this.mapRenderer) {
            this.mapRenderer.clearAllRenderObjects();
        }

        // 重置UI管理器
        if (this.uiManager) {
            this.uiManager.clearUIManager();
        }

        // 重置玩家统计管理器
        const playerStatsManager = PlayerStatsManager.getInstance();
        playerStatsManager.reset();

        LOG.log('BattleScene: 战斗场景重置完成');
    }

}